package com.lonely.fx;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
 * @date: 2022-07-08 17:04
 * @author: ztkj-hzb
 * @description: 多选框设置
 **/
public class CheckBoxSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox hBox = new HBox();
        hBox.setPadding(new Insets(100));
        hBox.setSpacing(30);

        Label label = new Label("请选择球类：");
        CheckBox checkBox1 = new CheckBox("篮球");
        CheckBox checkBox2 = new CheckBox("足球");
        CheckBox checkBox3 = new CheckBox("羽毛球");

        //设置默认选中
        checkBox1.setSelected(true);

        //设置为半选中状态
        checkBox2.setIndeterminate(true);

        //开启允许设置半选中状态，默认为false
        checkBox2.setAllowIndeterminate(true);

        hBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3);

        //设置选中事件
        hBox.getChildren().stream().filter(x -> x instanceof CheckBox).map(x -> (CheckBox) x)
                .forEach(x -> {
                    x.selectedProperty().addListener((observable, oldValue, newValue) -> {
                        System.out.println(x.getText() + "是否选中: " + x.isSelected());
                    });
                    x.indeterminateProperty().addListener((observable, oldValue, newValue) -> System.out.println(x.getText() + "--- 是否半选中：" + x.isIndeterminate()));
                });

        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();
    }
}
